import { useEffect, useMemo, useRef, useState } from "react";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Space,
  Select,
  Spin,
  Tabs,
  Row,
  Col,
  Dropdown,
  Modal,
} from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import manageService, { type PageListReq } from "@/api/services/mes/sopService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import type { SopDocumentManage } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import SopDocumentPage, { type SopDocumentHandles } from "./document";
import SopDocumentProductPage, {
  type SopDocumentProductHandles,
} from "./product";
import SendDocPage from "./sendDoc";

const { TextArea } = Input;

export default function SopDocumentManagePage() {
  const documentRef = useRef<SopDocumentHandles>(null);
  const productRef = useRef<SopDocumentProductHandles>(null);
  const sendDocRef = useRef<SendDocPageProps & { saveSendDoc: () => void }>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    code: undefined,
    name: undefined,
    type: undefined,
    status: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<SopDocumentManage[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [tableSize, setTableSize] = useState<"large" | "middle" | "small">(
    "middle"
  );
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<SopDocumentManage | null>(
    null
  );
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);

  const [sendDocVisible, setSendDocVisible] = useState(false);
  const [sendDocData, setSendDocData] = useState<SopDocumentManage | null>(
    null
  );
  const [sendDocLoading, setSendDocLoading] = useState(false);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 403;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const statusOptions = useDictionary("sop_document_status");
  const typeOptions = useDictionary("sop_document_type");

  const columns: ColumnsType<SopDocumentManage> = [
    {
      title: "文档编码",
      width: 120,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "文档名称",
      width: 120,
      key: "name",
      dataIndex: "name",
    },
    {
      title: "文档类型",
      width: 120,
      key: "type",
      dataIndex: "type",
      render: (_, record) => (
        <TableDictTag dictCode="sop_document_type" value={record.type ?? ""} />
      ),
    },
    {
      title: "状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag
          dictCode="sop_document_status"
          value={record.status ?? ""}
        />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  const [selectedValues, setSelectedValues] = useState<string[]>(() =>
    columns
      .filter((col) => col.key !== "operation")
      .map((col) => (col.key ? String(col.key) : ""))
  );

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  const filteredColumns = useMemo(() => {
    return [
      ...columns.filter(
        (col) =>
          selectedValues.includes(String(col.key)) || col.key === "operation"
      ),
    ].sort((a, b) => {
      const originalIndex = columns.findIndex((c) => c.key === a.key);
      const targetIndex = columns.findIndex((c) => c.key === b.key);
      return originalIndex - targetIndex;
    });
  }, [selectedValues]);

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    manageService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (sopDocumentManage: SopDocumentManage) => {
    setEditingData(sopDocumentManage);
    form.setFieldsValue(sopDocumentManage);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (sopDocumentManage: SopDocumentManage) => {
    setEditingData(sopDocumentManage);
    form.setFieldsValue(sopDocumentManage);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: SopDocumentManage) => {
    try {
      setSubmitLoading(true);

      //文档管理
      const deleteDocumentIds = documentRef.current?.getDeleteIds();
      const addDocuments = documentRef.current?.getAddList();
      const updateDocuments = documentRef.current?.getUpdateList();

      //关联产品
      const deleteProductIds = productRef.current?.getDeleteIds();
      const addProducts = productRef.current?.getAddList();
      const updateProducts = productRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteDocumentIds: deleteDocumentIds,
        addDocuments: addDocuments,
        updateDocuments: updateDocuments,
        deleteProductIds: deleteProductIds,
        addProducts: addProducts,
        updateProducts: updateProducts,
      };
      if (editingData) {
        await manageService.update(data);
        toast.success("更新文档集成功");
      } else {
        await manageService.add(data);
        toast.success("创建文档集成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await manageService.remove(selectedRowKeys);
      toast.success("删除文档集成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  //更新状态
  const updateStatus = async (status: string) => {
    if (selectedRowKeys.length === 0) {
      toast.error("请先选择要操作的文档集");
      return;
    }

    const selectedRows = list.filter((item) =>
      selectedRowKeys.includes(item.id)
    );
    const allSameStatus = selectedRows.every(
      (row) => row.status === selectedRows[0]?.status
    );
    if (!allSameStatus) {
      toast.error("请选择状态一致的文档集进行操作");
      return;
    }

    if (status === "published") {
      const allDraft = selectedRows.every((row) => row.status === "created");
      if (!allDraft) {
        toast.error("只有创建状态的文档集才能发布");
        return;
      }
    }
    if (status === "created") {
      const allDraft = selectedRows.every((row) => row.status === "published");
      if (!allDraft) {
        toast.error("只有发布状态的文档集才能取消发布");
        return;
      }
    }

    try {
      setLoading(true);
      await manageService.updateStatus(selectedRowKeys, status);
      if (status === "published") {
        toast.success("发布成功");
      } else if (status === "created") {
        toast.success("取消发布成功");
      } else {
        toast.success("工艺路线状态更新成功");
      }
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`更新状态失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const SendDoc = () => {
    if (selectedRowKeys.length === 0) {
      toast.error("请先选择要推送的文档集");
      return;
    }
    const selectedRows = list.filter((item) =>
      selectedRowKeys.includes(item.id)
    );
    if (selectedRows.length > 1) {
      toast.error("只能推送单个文档集");
      return;
    }
    const sopDocumentManage = selectedRows[0];
    if (sopDocumentManage.status === "published") {
      setSendDocVisible(true);
      setSendDocData(sopDocumentManage);
    } else {
      toast.error("只有发布状态的文档集才能推送");
    }
  };

  const saveSendDoc = async () => {
    if (sendDocRef.current) {
      setSendDocLoading(true);
      try {
        // 等待 saveSendDoc 完全执行完毕再关闭弹窗
        await sendDocRef.current.saveSendDoc();
        setSendDocVisible(false);
      } catch (error) {
        toast.error(`推送文档失败: ${error.message}`);
      } finally {
        setSendDocLoading(false);
      }
    }
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="code" label="文档编码">
            <Input placeholder="请输入文档编码" allowClear />
          </Form.Item>
          <Form.Item name="name" label="文档名称">
            <Input placeholder="请输入文档名称" allowClear />
          </Form.Item>
          <Form.Item name="status" label="状态">
             <Select options={statusOptions} allowClear style={{ width: 100 }}/>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <div className="flex justify-between mb-4">
          <div className="flex gap-2">
            <Button type="primary" onClick={handleAdd}>
              新增
            </Button>
            <Button
              danger
              disabled={selectedRowKeys.length === 0}
              onClick={handleDelete}
            >
              删除
            </Button>
            <Button.Group>
              <Button
                disabled={selectedRowKeys.length === 0}
                type="primary"
                onClick={() => updateStatus("published")}
              >
                发布
              </Button>
              <Button
                type="primary"
                disabled={selectedRowKeys.length === 0}
                onClick={(e) => {
                  e.stopPropagation();
                }}
                style={{ padding: 0, border: "none", boxShadow: "none" }}
              >
                <Dropdown
                  menu={{
                    items: [
                      {
                        key: "unpublish",
                        label: "取消发布",
                        onClick: () => updateStatus("created"),
                      },
                    ],
                  }}
                  placement="bottomRight"
                  trigger={["click"]}
                >
                  <span style={{ padding: "0 8px", cursor: "pointer" }}>▼</span>
                </Dropdown>
              </Button>
            </Button.Group>
            <Button
              danger
              disabled={selectedRowKeys.length !== 1}
              onClick={SendDoc}
            >
              推送文件
            </Button>
          </div>
          <TableToolbar
            onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
            onSizeChange={setTableSize}
            columns={columns}
            selectedValues={selectedValues}
            onColumnChange={setSelectedValues}
          />
        </div>
        <Table
          rowKey="id"
          size={tableSize}
          scroll={{ x: "max-content", y: tableScrollY }}
          loading={loading}
          pagination={{
            total,
            current: queryParams.page,
            pageSize: queryParams.pageSize,
            onChange: handlePageChange,
          }}
          columns={filteredColumns}
          dataSource={list}
          rowSelection={{
            type: "checkbox",
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedKeys) => {
              setSelectedRowKeys(selectedKeys as string[]);
            },
          }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑文档集" : "新增文档集"}
        width={900}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button type="primary" onClick={() => form.submit()}>
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="code"
                label="文档编码"
                rules={[{ required: true, message: "请填写文档编码" }]}
              >
                <Input placeholder="请输入文档编码" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="文档名称"
                rules={[{ required: true, message: "请填写文档名称" }]}
              >
                <Input placeholder="请输入文档名称" allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="type"
                label="文档类型"
                rules={[{ required: true, message: "请填写文档类型" }]}
              >
                <Select options={typeOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: "请填写状态" }]}
              >
                <Select options={statusOptions} allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="remark"
                label="备注"
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 21 }}
              >
                <TextArea />
              </Form.Item>
            </Col>
          </Row>
          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1",
                label: "文档管理",
                children: (
                  <SopDocumentPage
                    ref={documentRef}
                    parentId={editingData?.id}
                    status={editingData?.status}
                    isView={isView}
                  />
                ),
              },
              {
                key: "2",
                label: "关联产品",
                children: (
                  <SopDocumentProductPage
                    ref={productRef}
                    parentId={editingData?.id}
                    status={editingData?.status}
                    isView={isView}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>

      {/* 推送文档 */}
      <Modal
        title="推送文档"
        open={sendDocVisible}
        width="100%"
        style={{ top: 0, maxWidth: "98vw", padding: 10 }}
        styles={{
          body: {
            height: "calc(100vh - 200px)",
            overflow: "auto",
            padding: "10px 24px",
          },
          content: { maxWidth: "100vw", overflow: "hidden" },
          header: { padding: "16px 24px" },
          footer: { padding: "10px 24px" },
        }}
        onCancel={() => setSendDocVisible(false)}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={() => setSendDocVisible(false)}>取消</Button>
            <Button
              type="primary"
              onClick={saveSendDoc}
              disabled={sendDocLoading}
            >
              确定
            </Button>
          </div>
        }
      >
        <Spin spinning={sendDocLoading} tip="正在推送，请稍候...">
          <SendDocPage ref={sendDocRef} managerId={sendDocData?.id} />
        </Spin>
      </Modal>
    </Spin>
  );
}
